package com.yfqy.admin.resource;

import com.yfqy.admin.service.impl.AliyunOSSService;
import com.yfqy.admin.domain.vo.common.ResultVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;

@RestController
@RequestMapping("/api/internal/file")
public class FileUploadController {

    @Value("${yfqy.file.upload-dir}")
    private String uploadDir;

    private final AliyunOSSService aliyunOSSService;

    public FileUploadController(AliyunOSSService aliyunOSSService) {
        this.aliyunOSSService = aliyunOSSService;
    }

    @PostMapping("/upload2Local")
    public ResultVO<String> winUploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 创建存储目录
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            // 生成唯一文件名
            String filename = System.currentTimeMillis() + "_" + file.getOriginalFilename();
            Path filePath = uploadPath.resolve(filename);
            // 保存文件
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
            return ResultVO.data(uploadDir + filename);
        } catch (IOException e) {
            return ResultVO.fail("上传失败: " + e.getMessage());
        }
    }

    /**
     * 上传图片到阿里云oss服务器
     *
     * @param file
     * @param folder
     * @return
     */
    @PostMapping("/upload2AliYunOSS")
    public ResultVO<String> upload(@RequestParam("file") MultipartFile file,
                                   @RequestParam(value = "folder", defaultValue = "images") String folder) {
        String url = aliyunOSSService.upload(file, folder);
        return ResultVO.data(url);
    }

    @PostMapping("/batchUpload2AliYunOSS")
    public ResultVO<List<String>> uploadBatch(@RequestParam("files") MultipartFile[] files,
                                              @RequestParam(value = "folder", defaultValue = "images") String folder) {
        List<String> urls = aliyunOSSService.uploadBatch(files, folder);
        return ResultVO.data(urls);
    }

    @PostMapping("/deleteAliYunOSS")
    public ResultVO<Void> delete(@RequestParam String url) {
        aliyunOSSService.delete(url);
        return ResultVO.success();
    }

}
